﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace InDepth2Demo.Chapter3
{
    //通过例子来学习：泛型字典
    public class DectionaryDemo_1
    {
        public static void Call()
        {
            string text = @"Do you like green eggs and ham?
                            I do not like them,Sam-I-am.
                            I do not like green eggs and ham.";
            var texts = CountWords(text);
            foreach (var item in texts)
            {
                String key = item.Key;
                int value = item.Value;
                Console.WriteLine("{0}:{1}", item.Key, item.Value);
            }
        }

        public static void Call2()
        {
            string text = @"Do you like green eggs and ham?
                            I do not like them,Sam-I-am.
                            I do not like green eggs and ham.";
            Dictionary<string, int> texts = CountWords(text);
            foreach (KeyValuePair<string, int> item in texts)
            {
                Console.WriteLine("{0}:{1}", item.Key, item.Value);
            }
        }

        /// <summary>
        /// 单词计数方法
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        static Dictionary<string, int> CountWords(string text)
        {
            Dictionary<string, int> frequencies = new Dictionary<string, int>();
            string[] words = Regex.Split(text, @"\W+");//将文本分解成单词
            //foreach (var item in words)//文本末尾有个空字符串、是文本末尾的.句号造成的
            //{
            //    Console.WriteLine(item);
            //}
            foreach (var val in words)
            {
                var word = val.ToLower(); //解决没有考虑do和Do分开计数

                if (frequencies.ContainsKey(word))
                {
                    frequencies[word]++;
                }
                else
                {
                    frequencies[word] = 1;
                }
            }
            return frequencies;
        }
    }
}
